package test.model;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import test.model.table.ButtonRenderer;
import test.model.table.ImageRenderer;

public class ContactTableModel extends AbstractTableModel{
	
	private String[] columnNames = {"Image", "Name", "Phone", ""};
	
	private List<ContactItem> items = new ArrayList<ContactItem>();
	private List<ContactItem> allData = new ArrayList<ContactItem>();
	private String filterKeywork = "";
	
	public void setContacts(ArrayList<ContactItem> lst){
		allData.clear();
		allData.addAll(lst);
		
		items.clear();
		items.addAll(lst);
	}
	
	public void addItem(ContactItem item){
		allData.add(item);
		
		if(item.getName().contains(filterKeywork))
			items.add(item);
	}
	
	public void removeItem(ContactItem item){
		allData.remove(item);
		items.remove(item);
		fireTableDataChanged();
	}
	
	public void removeItem(int idx){
		ContactItem item = items.get(idx);
		allData.remove(item);
		items.remove(item);
		fireTableDataChanged();
	}
	
	public ContactItem getItemAt(int rowIndex){
		return items.get(rowIndex);
	}
	
	public void filter(String kw){
		
		if(kw.toLowerCase().equals(filterKeywork))
			return;
		
		filterKeywork = kw.toLowerCase();
		items.clear();
		
		if(kw.length()<=0){
			items.addAll(allData);
			fireTableDataChanged();
			return;
		}
		
		for(ContactItem itm: allData){
			if(itm.getName().toLowerCase().contains(filterKeywork))
				items.add(itm);
			fireTableDataChanged();
		}
	}

	@Override
	public int getRowCount() {
		return items.size();
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}
	
	@Override
	public String getColumnName(int column) {
		return columnNames[column];
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		switch(columnIndex){
			case 0:
				return items.get(rowIndex).getImage();
				
			case 1:
				return items.get(rowIndex).getName();
				
			case 2:
				return items.get(rowIndex).getPhone();
				
//			case 3:
//				return items.get(rowIndex).getPhone();
		}
		return items.get(rowIndex);
	}
	
	@SuppressWarnings("unchecked")
	public Class<?> getColumnClass(int columnIndex){
		switch(columnIndex){
			case 0:
				return ImageRenderer.class;
			
			case 1:
				return String.class; 
			
			case 2:
				return String.class;
			
			case 3:
				return ButtonRenderer.class;
		}
		return null;
	}
	
	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
	    return true;
	}

}
